//
//  ShoppingViewController.swift
//  DollBuy
//
//  Created by 郑东喜 on 2016/12/2.
//  Copyright © 2016年 郑东喜. All rights reserved.
//  购物车界面

import UIKit
import WebKit


class ShoppingViewController : WKBaseViewController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if (localSave.object(forKey: userToken) != nil) {
            let urlStr = (shooppingCarURL) + ("?devtype=1&token=") + self.token
    
            //防止网页容器为空的时候，造成异常、奔溃
            if self.webView == nil {
                return
            } else {
                self.webView.load(URLRequest.init(url: URL.init(string: urlStr)!))
            }
            
        } else {
            //设置状态栏颜色
            self.navigationController?.navigationBar.barTintColor = commonBtnColor
            
            //文字颜色
            self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
            
            //加载本地索引为0的缓存
             let urlStr = "http://\(yuMing)/app/index.aspx?devtype=1" + "&token=" + self.token
            
            //判断是否包含域名
            if urlStr.contains(comStrURL) {
                let url1 = URL.init(string: urlStr)
                self.urlRequestCache = NSURLRequest(url: url1!, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 10)
                
                self.webView.load(self.urlRequestCache as URLRequest)
            } else {
                return
            }

            
            let alertView = UIAlertController.init(title: "提示", message: "请登录", preferredStyle: .alert)
            alertView.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: { (nil) in
                
                //清除URL保存的值
                mainIndexArray.removeAllObjects()
                fwqArray.removeAllObjects()
                commuArray.removeAllObjects()
                shoppingCarArray.removeAllObjects()
                jiaoYIArray.removeAllObjects()
                zhongjiangArray.removeAllObjects()
                duihuanArray.removeAllObjects()
                fenxiangArray.removeAllObjects()

                
                //切换效果
                let tabbarVC = UIApplication.shared.keyWindow?.rootViewController as! UITabBarController
                tabbarVC.selectedIndex = 0
                
                Animated.vcWithTransiton(vc: tabbarVC, animatedType: "kCATransitionFade", timeduration: 1)
            }))
            
            alertView.addAction(UIAlertAction.init(title: "确定", style: .default, handler: { (nil) in
                
                //设置状态栏颜色
                self.navigationController?.navigationBar.barTintColor = UIColor.white
                
                //文字颜色
                self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.black]
                
                self.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(LoginView(), animated: true)
                
                self.navigationController?.navigationBar.barTintColor = UIColor.white
                
                //文字颜色
//                self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.black]
                
                
                UIApplication.shared.statusBarStyle = .default
                self.hidesBottomBarWhenPushed = false

            }))

            UIApplication.shared.keyWindow?.rootViewController?.present(alertView, animated: true, completion: nil)
            
            return
        }
        

    }
    
    override func viewDidLoad() {
       
        super.viewDidLoad()
        
        
        //取出本地token，进行拼接
        if (localSave.object(forKey: userToken) != nil) {
            
            self.navigationItem.title = "购物车"
            //背景色--白色
            view.backgroundColor = UIColor.white
            
            
            //取最后一个链接URL，加载当前视图
            if shoppingCarArray.count > 1 {
                
                
                let urlStr = ((shoppingCarArray.lastObject) as! String)
                
                webView.load(URLRequest.init(url: URL.init(string: urlStr)!))
            } else  {
                DispatchQueue.main.async {
                    
                    let urlStr = (shooppingCarURL) + ("?devtype=1&token=") + self.token
                    
                    
                    if urlStr.contains(comStrURL) {
                        let url = URL.init(string: urlStr)
                        
                        
                        //根据是否有网络状态加载断网图片
                        StatusBarCheck.shared.networkingStatesFromStatebar { (result) in
                            
                            if result == "notReachable" {
                                DispatchQueue.main.async {
                                    
                                    DispatchQueue.main.async {
                                        
                                        self.urlRequestCache = NSURLRequest.init(url: url!, cachePolicy: .returnCacheDataElseLoad, timeoutInterval: 0)
                                        
                                    }
                                }
                        
                            } else {
                                DispatchQueue.main.async {
                                    
                                    self.urlRequestCache = NSURLRequest(url: url!, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 10)
                                    
                                    self.webView.load(self.urlRequestCache as URLRequest)
                                }
                            }
                        }

                    } else {
                        CustomAlertView.shared.alertWithTitle(strTitle: "请下拉刷新")
                        
                    }
                    
                }
                
            }
            
        } else {
            let alertView = UIAlertController.init(title: "提示", message: "请登录", preferredStyle: .alert)
            alertView.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: nil))
            
            alertView.addAction(UIAlertAction.init(title: "确定", style: .default, handler: { (nil) in
                
                self.navigationController?.pushViewController(LoginView(), animated: true)
            }))
            
        }
    }
    
    /**
     *  JS 调用 swift 时 webview 会调用此方法
     *
     *  @param userContentController  webview中配置的userContentController 信息
     *  @param message                JS执行传递的消息
     */
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        textView.text = self.url
        
        url = (navigationAction.request.url?.absoluteString)!

        if navigationAction.navigationType == WKNavigationType.linkActivated || url == "http://\(yuMing)/app/order_pay.aspx" {
            
            //如果为本身或者本身携带#的url进行自身刷新。
            if self.url.contains("?") {
                self.url = self.url + ("&devtype=1&token=") + (token)
            } else {
                self.url = self.url + ("?devtype=1&token=") + (token)
            }
            
            
            //XFLog(message: url)
                shoppingCarArray.add(url)
            aaa(str: self.url)
            
            decisionHandler(.cancel)
            
        } else {
            decisionHandler(.allow)
        }
    }
    
    /// 跳转的控制器
    ///
    func aaa(str : String) -> Void {
        
        let vvv = ShoppingReplaceView()
        vvv.url = str
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vvv, animated: true)
        self.hidesBottomBarWhenPushed = false
        
    }
}




